package org.cy.websocket.stomp.timer;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 时钟任务调度器
 *
 * Created in 2021-05-15 17:52
 *
 * @author cao.yong
 */
public class TimedTaskScheduler {
    private final ConcurrentMap<String, Timer> TIMERS = new ConcurrentHashMap<>(0);

    public void start(String name, TimerProcessor processor, long delay) {
        Timer timer = new Timer("Timer-" + name);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                processor.proc();
            }
        }, delay, delay);
        TIMERS.putIfAbsent(name, timer);
    }

    public void stop(String name) {
        if (TIMERS.containsKey(name)) {
            Timer timer = TIMERS.get(name);
            if (null != timer) {
                timer.cancel();
            }
            TIMERS.remove(name);
        }
    }
}
